package com.astrocsr.action.common;
 
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.astrocsr.business.StatementManager;
import com.astrocsr.business.UserManager;
import com.astrocsr.common.util.DateUtil;
import com.astrocsr.domain.model.DownloadModel;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Controller("downloadAction")
@Scope("prototype")
public class DownloadAction extends ActionSupport implements ModelDriven<DownloadModel>, 
	ServletContextAware {

	private static final long serialVersionUID = 1L;
	static final Logger log = Logger.getLogger(DownloadAction.class);
    static final SimpleDateFormat dateFormatterIn 	= new SimpleDateFormat("yyyy-MM-dd");
    static final SimpleDateFormat dateFormatterOut 	= new SimpleDateFormat("dd/MM/yy");
    
	private DownloadModel model = new DownloadModel();
	private InputStream fileInputStream;
	private String fileName;
 
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private StatementManager statementManager;
	
	@Override
	public DownloadModel getModel() {
		return model;
	}
	public InputStream getFileInputStream() {
		return fileInputStream;
	}
	public String getFileName() {
		return fileName;
	}

	/**
	 * download pdf
	 */
	public String execute() throws Exception {
		try {

			String realPath = context.getRealPath("") + File.separator; 
			final String resourcePath = realPath + "resource" + File.separator;
			System.out.println("resourcePath = " + resourcePath);
			
			Long userId = model.getUserId();
			String stmtDate = model.getStmtdate();
			
			if (userId != null && StringUtils.isNotBlank(stmtDate)) {
				Date statementDate = DateUtil.createDateLocalSlash(stmtDate);
				fileName = userId + "_" + DateUtil.formatUniversal(statementDate) + ".pdf";
	            
	    		byte[] outBytes = statementManager.getPDFData(userId, statementDate, resourcePath);
	            fileInputStream = new ByteArrayInputStream(outBytes);
			}

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return SUCCESS;
	}
	
	private ServletContext context;
    @Override
    public void setServletContext(ServletContext ctx) {
        this.context=ctx;
    }
}